//Nathan Popham
//4003-573-01: Procedural Shading
//Lab 2
//
//Phong fragment shader
// Implements Phong shading using an interpolated normal, eye vector and point
// position passed in from vertex shader. In addition, if multiple lights are
// used, the uniform variable NumLights should be set to the number of active
// lights (it's assumed that lights will be in consecutive order, i.e. if 
// there are three active lights GL_LIGHT0, GL_LIGHT1, and GL_LIGHT2 will be
// used). Lights can be positional or directional.

varying vec3 N, V, pos;

uniform int NumLights;

void main()
{

    vec4 ambient = vec4(0.0, 0.0, 0.0, 1.0); 
	vec4 diffuse = vec4(0.0, 0.0, 0.0, 1.0); 
	vec4 specular = vec4 (0.0, 0.0, 0.0, 1.0);
   
    //for each light
    for(int i = 0; i < NumLights; i++)
    {
        ambient += gl_FrontMaterial.ambient * gl_LightSource[i].ambient;

        vec3 L;

        if(gl_LightSource[i].position[3] == 0.0)        
            L = normalize(vec3((gl_LightSource[i].position)));
        else 
            L = normalize(vec3(gl_LightSource[i].position) - pos);


        float NdotL = max(dot(N, L), 0.0);
        diffuse += NdotL * (gl_FrontMaterial.diffuse * gl_LightSource[i].diffuse);

        if (NdotL > 0.0) 
        {
            vec3 R = normalize (reflect(-L, N));
            float RdotV = max(dot(R, V), 0.0);
            specular += gl_FrontMaterial.specular * gl_LightSource[1].specular * pow(RdotV,gl_FrontMaterial.shininess);
        }
    }

	gl_FragColor = ambient + diffuse + specular;
} 
